package dk.sdu.flexibus.addresssuggestor;

import java.util.ArrayList;
import java.util.HashSet;

import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;

public class AddressSuggester implements LocationListener {	

	private static AddressSuggester instance;
	
	private HashSet<AddressSuggestionListener> suggestionListeners = new HashSet<AddressSuggestionListener>();
	private LocationManager locationManager;
	
	private static final int TEN_SECONDS = 10000;
	private static final int TEN_METERS = 10;
	
	private AddressSuggester(){
		
	}
	
	public static AddressSuggester getAddressSuggester(LocationManager lm, String... providers){
		boolean geocoderAvailable =
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();
        String provider = LocationManager.NETWORK_PROVIDER;
		if(instance == null){
			instance = new AddressSuggester();
			if (lm.isProviderEnabled(provider) && geocoderAvailable) {
	            lm.requestLocationUpdates(provider, TEN_SECONDS, TEN_METERS, instance);
	            instance.locationManager = lm;
			}
		}
		return instance;
	}
	
	public void subscribeAddressSuggestions(AddressSuggestionListener listener) {
		suggestionListeners.add(listener);
	}

	public void unsubscribeAddressSuggestions(AddressSuggestionListener listener) {
		suggestionListeners.remove(listener);
	}
	
	public void notifySuggestionListeners(ArrayList<String> result) {
		for (AddressSuggestionListener a : suggestionListeners) {
			a.suggestAddresses(null);
		}
	}
	
    @Override
    public void onLocationChanged(Location location) {
//    	if (geocoderAvailable){
//			(new ReverseGeocodingTask(context)).execute(new Location[] {location});
//    	}
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}
